package TitleScreen;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.SocketException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import Lobby.cLobby;
import Lobby.mLobby;
import Lobby.vLobby;
/**
 * 
 * @author Thomas Felder
 *
 */


public class cTitleScreen implements ActionListener {
	
	private vTitleScreen view;
	private mTitleScreen model;
	/**
	 * Steuert die Interaktion zwischen View und Model.
	 * 
	 * @param vTitleScreen view
	 * @param mTitleScreen model
	 * @author Thomas Felder
	 */
	public cTitleScreen(vTitleScreen view, mTitleScreen model) {
		this.view = view;
		this.model = model;

		view.form.jBtn_login.addActionListener(this);
		view.form.jBtn_register.addActionListener(this);

	}

	/**
	 * @author Christopher Vogel
	 */
	public void goToLobby() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				cTitleScreen.this.view
						.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
				cTitleScreen.this.view.dispose();
				mLobby model = new mLobby();
				vLobby view = new vLobby(model);
				boolean isLoaded = view.isActive();
				view.repaint();
				new cLobby(model, view);
				ServerListener.ServerListener.Lobby = model;
			}
		});
	}

	@Override
	/**
	 * @author Christopher Vogel and Thomas Felder
	 */
	public void actionPerformed(ActionEvent e) {
		// no if-else function in case of additional buttons
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					if (e.getActionCommand().equals("Login")) {
						String ErrorMessage = model.login(
								view.form.jTF_UserName.getText(), new String(
										view.form.jTF_password.getPassword()));
						if (ErrorMessage == null) {
							goToLobby();
						} else {
							JOptionPane.showMessageDialog(null, ErrorMessage,
									"Login", 2); // deprecated
						}
					}

					if (e.getActionCommand().equals("Register")) {
						String ErrorMessage = model.register(
								view.form.jTF_UserName.getText(), new String(
										view.form.jTF_password.getPassword()));
						if (ErrorMessage == null) {
							goToLobby();
						} else {
							JOptionPane.showMessageDialog(null, ErrorMessage,
									"Registration", 2); // deprecated
						}
					}
				} catch (SocketException e1) {
					JOptionPane.showMessageDialog(null,
							"Could not connect to server!", "Fatal error", 2);
				}
			}
		});
	}

}
